#!/usr/bin/env python

import pygame, sys, math, random

from accel import AccelControl

from vector import *

class Man(object):

	def __init__(self):
		self.y=random.randint(-310,310)
		self.x=-240
		self.frame=0

	def move(self):
		self.frame=(self.frame+1)%4
		self.x+=1

	def collide(self, r):
		return r.colliderect(pygame.Rect(self.x-4,self.y-8,8,16))

	def draw(self, surface):
		surface.blit(man[self.frame], (240+self.x-8,320+self.y-8))

def input(events): 
   for event in events:
	   if event.type == pygame.QUIT: 
		   sys.exit(0)
	   elif event.type == pygame.KEYDOWN:
		   # scancode 177 = aux
		   if event.key == pygame.K_ESCAPE or event.scancode==177:
			   sys.exit(0)
	   

def load_sound(name):
    class NoneSound:
        def play(self): pass
    if not pygame.mixer:
        return NoneSound()
    try:
        sound = pygame.mixer.Sound(name)
    except pygame.error, message:
        print "Cannot load sound:", name
        raise SystemExit, message
    return sound


if __name__=="__main__":
	pygame.init()

	if not pygame.mixer: print 'Warning, sound disabled'

	#window = pygame.display.set_mode((480, 640))
	window = pygame.display.set_mode((480, 640), pygame.FULLSCREEN|pygame.HWSURFACE|pygame.OPENGL)
	
	screen = pygame.display.get_surface() 

	# loading gfx
	skidmark=pygame.image.load("data/skidmark.png")
	bloodimg=pygame.image.load("data/blood.png")
	skidmarks=[]

	car=pygame.image.load("data/car.png")
	cars=[]
	for i in range(0,360,10):
		cars+=[pygame.transform.rotate(car, 360-i)]
		skidmarks+=[pygame.transform.rotate(skidmark, 360-i)]

	print "Car:", cars[0].get_flags(), cars[0].get_bitsize()

	man=[]
	for i in range(0,4):
		man+=[pygame.image.load("data/man%d.png"%i)]

	# loading sounds
	#sound=load_sound("boing.wav")
	splat=load_sound("data/splat.ogg")
	scream=load_sound("data/scream.ogg")
	skid=load_sound("data/skid.ogg")
	
	a=AccelControl()

	# the accelerometer position when we start.
	origin=a.read()

	ox,oy,oz=origin

	# car x,y
	bx=0
	by=0

	# last x,y for direction
	lx=0
	ly=0

	# speed
	dx=0
	dy=0

	# sound playing?
	skidchannel=None

	# keeping coordinates/objects
	skids=[]
	men=[]
	blood=[]

	if pygame.font:
		font = pygame.font.Font(None, 16)
		
	points=0

	print "Cars!"
	while True: 
		input(pygame.event.get())

		# input: 
		acx,acy,acz=a.read()

		ax=(ox-acx)/100.0
		ay=(oy-acy)/100.0
		
		# x is inversed
		ax*=-1
		
		dx+=ax
		dy+=ay

		# friction
		dx*=0.9
		dy*=0.9

		# max speed
		if vlen((dx,dy))>25:
			dx,dy=scale(normal((dx,dy)), 25)			

		# "game logic" 
		bx+=dx
		by+=dy

		# edges
		if bx<-220:
			dx*=-0.9
			bx=-220
		if bx>220:
			dx*=-0.9
			bx=220
		if by<-300:
			dy*=0.9
			by=-300
		if by>300:
			dy*=0.9
			by=300
					
		d=direction(bx-lx, by-ly)*(180/math.pi)
		#d=(d+270)%360 # our images start with up as 0 

		d=int(d/10)

		# skids
		if vlen((dx-ax, dy-ay))>20:
			nd=scale(normal((dx,dy)), 16)
			skids+=[(bx-nd[0],by-nd[1],d)]
			if len(skids)>20:
				skids=skids[1:]
			if skidchannel==None or not skidchannel.get_busy():
				skidchannel=skid.play()

		# men

		if random.random()>0.95:
			men.append(Man())
		
		for m in men:
			m.move()
			r=pygame.Rect(bx-10,by-10,20,20) # the car
			if m.collide(r):
				men.remove(m)
				splat.play()
				scream.play()
				points+=1
				blood.append((m.x, m.y))
				if len(blood)>10:
					blood=blood[1:]

		# draw it all

		# blank
		screen.fill((0,0,0))

		# score
		if pygame.font:
			text = font.render("%d"%points, 1, (255,255,255))
			screen.blit(text,(0,0))

		# draw skids
		for s in skids:
			screen.blit(skidmarks[s[2]], (240+s[0]-3,320+s[1]-3))

		# draw men
		for m in men:
			m.draw(screen)

		# draw blood
		for b in blood:
			screen.blit(bloodimg, (240+b[0]-8,320+b[1]-8))

		screen.blit(cars[d], (240+bx-16,320+by-16))

		lx=bx
		ly=by
		
		pygame.display.flip()

		# dump debug things
		
		sys.stdout.write("\r% 5.2f % 5.2f % 5.2f - % 5.2f % 5.2f - %d"%(vlen((dx,dy)), dx,dy,ax,ay,d))
		sys.stdout.flush()


